<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%
    /* 两种方法解决网站相对路径问题
        一是使用base标签
    */
    String basePath = request.getContextPath() + "/";
%>
<html>
<head>
    <meta charset="utf-8">
    <title>产品页</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
          content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>Insert title here</title>
    <base href="<%=basePath%>">
    <%--<link rel="stylesheet" href="../../layui/css/layui.css">--%>

</head>
<body>

<form class="layui-form" lay-filter="boardFilter">
    <div style="width:100%;margin-top: 20px;">
        <blockquote class="layui-elem-quote quoteBox">
            <label style="margin-left: 20px;" style="" class="layui-label">ID：</label>

            <div style="width: 120px;" class="layui-inline">
                <input type="text" name="productId" placeholder="请输入ID"
                       autocomplete="off" class="layui-input">
            </div>

            <label style="margin-left: 20px;" style="" class="layui-label">产品名称：</label>

            <div style="width: 120px;" class="layui-inline">
                <input type="text" name="productName" placeholder="请输入名称"
                       autocomplete="off" class="layui-input">
            </div>

            <label style="margin-left: 20px;" class="layui-label">产地：</label>

            <div style="width: 120px;" class="layui-inline">
                <input type="text" name="productLocation" placeholder="请输入产地"
                       autocomplete="off" class="layui-input">
            </div>

            <label style="margin-left: 20px;" class="layui-label">分类：</label>

            <div style="width: 120px;" class="layui-inline">
                <select name="categoryId" style="width:100%;" lay lay-verify="required">
                    <option value=""></option>
                </select>
            </div>
            <div class="layui-inline">
                <button id="searchBtn" class="layui-btn"
                        type="button" lay-filter="productTable">
                    <i class="layui-icon layui-icon-search"></i>搜索
                </button>
            </div>
            <div class="layui-inline">
                <button type="reset" class="layui-btn layui-btn-warm">
                    <i class="layui-icon layui-icon-release"></i>重置
                </button>
            </div>
            <div class="layui-inline">
                <button type="button" class="layui-btn" id="addBtn">
                    <i class="layui-icon layui-icon-add-1"></i>添加
                </button>
            </div>
        </blockquote>
    </div>
</form>

<script type="text/html" id="btnGroup">
    <shiro:hasPermission name="crm:product:edit"><a class="layui-btn layui-btn-xs"
                                                    lay-event="edit">编辑</a></shiro:hasPermission>
    <shiro:hasPermission name="crm:product:delete"><a class="layui-btn layui-btn-danger layui-btn-xs"
                                                      lay-event="delete">删除</a></shiro:hasPermission>
</script>

<table class="layui-hide" id="productTable" lay-filter="productTable"></table>
<!-- 编辑添加框 -->
<!-- form外面要有一个div-->
<div id="myform-div" class="layui-hide">
    <form class="layui-form" lay-filter="myform">
        <div style="margin-top: 15px;" class="layui-form-item">
            <label class="layui-form-label">产品编号：</label>
            <div class="layui-input-inline">
                <input type="text" name="id" readonly="readonly" style="width: 250px;"
                       placeholder="由系统设置" autocomplete="off" class="layui-input"/>
            </div>
        </div>
        <div style="width:100%;" class="layui-form-item">
            <label class="layui-form-label">产品名称：</label>
            <div class="layui-input-inline">
                <input type="text" name="name" lay-verify="required" style="width: 250px;"
                       placeholder="请输入产品名称" autocomplete="off" class="layui-input"/>
            </div>
        </div>
        <div style="width: 100%" class="layui-form-item">
            <label class="layui-form-label">产品分类：</label>
            <div class="layui-inline" style="width: 250px;">
                <select name="categoryId" lay lay-verify="required">
                    <option value=""></option>
                </select>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">产品型号：</label>
            <div class="layui-input-inline">
                <input type="text" name="version" lay-verify="required" style="width: 250px;"
                       placeholder="请输入产品型号(软件系统版本号)" autocomplete="off" class="layui-input">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">产地：</label>
            <div class="layui-input-inline">
                <input type="text" name="location" lay-verify="required" style="width: 250px;"
                       placeholder="请输入产品产地" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item" style="display: none;">
            <label class="layui-form-label">价格单位：</label>
            <div class="layui-input-inline">
                <input type="text" name="unit" style="width: 150px;"
                       autocomplete="off" class="layui-input" value="元(人民币)">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">价格：</label>
            <div class="layui-input-inline">
                <input type="text" name="price" lay-verify="required" style="width: 250px;" onkeyup="checknum(this)"
                       placeholder="价格单位：元(人民币)" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div style="width:100%;" class="layui-form-item">
            <label class="layui-form-label">备注：</label>
            <div class="layui-input-inline">
                    <textarea name="remarks" style="width: 250px; height:100px;"
                              placeholder="请输入备注信息" class="layui-textarea"></textarea>
            </div>
        </div>
        <button type="button" lay-submit lay-filter="formSubmit"
                id="submitButton" class="layui-hide"></button>
    </form>
</div>

<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script src="../../layui/layui.all.js"></script>
<script src="../../js/myutil.js"></script>

<script>



    layui.use(['table', 'form', 'tree', 'layer'], function () {
        var table = layui.table;
        var layer = layui.layer;
        var form = layui.form;
        var $ = layui.$;

        var productTable = table.render({
            elem: '#productTable'
            , url: 'product/findProduct'
            , cellMinWidth: 80 //全局定义常规单元格的最小宽度，layui 2.2.1 新增
            , cols: [[
                {field: 'id', title: '产品编号', sort: true, align: 'center'}
                , {field: 'name', title: '产品名称', align: 'center'}
                , {field: 'location', title: '产地', sort: true, align: 'center'}
                , {field: 'version', title: '型号/版本号', align: 'center'}
                , {field: 'unit', title: '单位', align: 'center'} //minWidth：局部定义当前单元格的最小宽度，layui 2.2.1 新增
                , {field: 'price', title: '价格', sort: true, align: 'center'}
                , {field: 'remarks', title: '备注', align: 'center'}
                , {
                    field: 'categoryName', title: '分类', sort: true, align: 'center', templet: function (data) {
                        return data.category.name;
                    }
                }
                , {
                    fixed: 'right',
                    title: "操作",
                    align: 'center',
                    width: "10%",
                    toolbar: '#btnGroup'
                }
            ]]
            , page: true
        });

        //监听表格内的事件
        table.on('tool(productTable)', function (obj) {
            var data = obj.data;

            if (obj.event === 'edit') {
                updateProduct(data);
            } else if (obj.event === 'delete') {
                layer.confirm('确定要删除该产品吗？', function (index) {
                    layer.close(index);
                    deleteProduct(data);
                });
            }
        });

        function deleteProduct(data) {
            var load = null;
            $.ajax({
                type: "POST",
                url: "${pageContext.request.contextPath}/product/deleteProduct",
                data: {
                    "id": data.id
                },
                dataType: "json",
                //请求前执行，无论请求是否成功
                beforeSend: function () {
                    //显示加载动画
                    load = layer.load(2);
                },
                complete: function () {
                    //关闭加载动画
                    layer.close(load);
                },
                success: function (data) {
                    if (data.success) {
                        //隐藏表单
                        hideDiv();
                        //操作成功 重新加载表格数据
                        layui.layer.open({
                            content: '删除成功!',
                            btn: ['确认'],
                            yes: function (index, layero) {
                                //执行重载
                                layer.closeAll();
                                table.reload('productTable', {
                                    page: {
                                        curr: 1 //重新从第 1 页开始
                                    }
                                });
                            },
                            cancel: function () {
                                //执行重载
                                layer.closeAll();
                                table.reload('productTable', {
                                    page: {
                                        curr: 1 //重新从第 1 页开始
                                    }
                                });
                            },
                        })
                    } else {
                        layer.msg(data.msg);
                    }
                },
                error: function () {
                    //隐藏表单
                    hideDiv();
                    //操作成功 重新加载表格数据
                    layui.layer.open({
                        content: '删除失败!',
                        btn: ['确认'],
                        yes: function (index, layero) {
                            layer.closeAll();
                        },
                        cancel: function () {
                            layer.closeAll();
                        },
                    })
                }
            });
        }

        function updateProduct(data) {
            //设置password为自定义检验
            showProductDiv('编辑产品');
            //设置值
            form.val('myform', {
                "id": data.id,
                "name": data.name,
                "location": data.location,
                "version": data.version,
                "unit": "元(人民币)",
                "price": data.price,
                "repertory": data.repertory,
                "remarks": data.remarks,
                "categoryId": data.categoryId
            });

            formUrl = "product/editProduct";
        }


        //搜索功能
        var active = {
            reload: function () {
                var productId = $("input[name='productId']");
                var productName = $("input[name='productName']");
                var productLocation = $("input[name='productLocation']");
                var categoryId = $("select[name='categoryId']");
                //执行重载
                productTable.reload({
                    where: {
                        "id": productId.val(),
                        "name": productName.val(),
                        "location": productLocation.val(),
                        "categoryId": categoryId.val()
                    }
                });
            }
        };
        $('#searchBtn').on('click', function () {
            active['reload'] ? active['reload'].call(this) : '';
        });

        //监听表单提交按钮
        form.on('submit(formSubmit)', function (data) {
            var but = data.elem; //获取点击的按钮
            var loadanima = null;
            var formdata = data.field; //读取form表单中的数据 ,键值对形式
            $.ajax({
                type: "POST",
                url: formUrl,
                data: formdata,
                dataType: "json",
                //请求前执行
                beforeSend: function () {
                    //给按钮添加禁用样式
                    but.className += " layui-btn-disabled";
                    //显示加载动画
                    loadanima = layer.load(2);
                },
                //请求完成执行，无论请求是否成功
                complete: function () {
                    //去除禁用属性
                    but.className = but.className.replace("layui-btn-disabled", "");
                    //关闭加载动画
                    layer.close(loadanima);
                },
                success: function (data) {
                    if (data.success) { //成功
                        //隐藏表单
                        hideDiv();
                        //操作成功 重新加载表格数据
                        layui.layer.open({
                            content: '操作成功!',
                            btn: ['确认'],
                            yes: function (index, layero) {
                                //执行重载
                                layer.closeAll();
                                table.reload('productTable');
                            },
                            cancel: function () {
                                //执行重载
                                layer.closeAll();
                                table.reload('productTable');
                            },
                        })
                    } else { //失败
                        //隐藏表单
                        hideDiv();
                        //操作成功 重新加载表格数据
                        layui.layer.open({
                            content: data.msg,
                            btn: ['确认'],
                            yes: function (index, layero) {
                                layer.closeAll();
                            },
                            cancel: function () {
                                //执行重载
                                layer.closeAll();
                            },
                        });
                    }

                },
                error: function () {
                    layer.msg("服务器开小差了，请稍后再试...");
                }
            });
            return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
        });

        //点击添加按钮后的处理
        $('#addBtn').click(function () {
            //显示表单
            showProductDiv('添加产品');
            //设置值
            form.val('myform', {
                "id": "",
            });
            //设置form表单提交地址
            formUrl = "product/addProduct"; //重要，必填属性
        });

        function hideDiv() {
            layer.closeAll('page');
        }

        //显示添加表单
        function showProductDiv(title) {
            var html = '';
            var window = layer.open({
                type: 1,
                title: title,
                closeBtn: 2,
                area: ['400px', '500px'],
                btn: ['确定', '取消'],
                btn1: function () {
                    $("#submitButton").click();
                },
                shadeClose: false,
                content: '<div id="show-form-div"></div>',
                end: function () {
                    $('#myform-div').html(html);
                }
            });
            html = $('#myform-div').html();
            $('#myform-div').html("");
            $('#show-form-div').html(html);
            return window;
        }

        $(function () {
            $.ajax({
                url: "product/findCategory",
                type: "POST",
                dataType: "json",
                beforeSend: function () {
                    loading = layer.load();
                },
                success: function (data) {
                    console.log($("select[name='categoryId']"));
                    var html = '';
                    var c = data.categorys;
                    for (i = 0; i < c.length; i++) {
                        html += "<option value='" + c[i].id + "'>" + c[i].name + "</option>";
                    }
                    $("select[name='categoryId']").append(html);//往下拉菜单里添加元素
                    layui.form.render('select', 'boardFilter');
                },
                error: function () {
                    layer.msg("服务器开小差了!");
                },
                complete: function () {
                    layer.close(loading);
                }

            });
        });
    });

</script>
</body>
</html>